package fr.sedoo.metadata.client.ui.widget.field.impl;

import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.message.MetadataMessage;
import fr.sedoo.metadata.client.ui.label.StatusLabelProvider;
import fr.sedoo.metadata.client.ui.label.UpdateRythmLabelProvider;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.client.ui.widget.field.primitive.ListBoxField;
import fr.sedoo.metadata.shared.domain.MetadataDTO;

public class UpdateRythm extends ListBoxField {

	public UpdateRythm() {
		super();
		init();
	}

	private void init() {
		listBox.clear();
		listBox.addItem(MetadataMessage.INSTANCE.selectItem(), FieldConstant.UNSELECTED_ID);
		Map<String, String> labels = UpdateRythmLabelProvider.getLabels();
		Iterator<Entry<String, String>> iterator = labels.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry<java.lang.String, java.lang.String> entry = iterator.next();
			listBox.addItem(entry.getValue(), entry.getKey());
		}
	}

	@Override
	public void display(MetadataDTO metadata) {
		ElementUtil.show(label);
		ElementUtil.hide(listBox);
		label.setText(StatusLabelProvider.getLabel(StringUtil.trimToEmpty(metadata.getTemporalExtentPart().getUpdateRythm())));
	}

	@Override
	public void flush(MetadataDTO metadata) {
		if (listBox.getSelectedIndex() == UNSELECTED_ID_INDEX) {
			metadata.getTemporalExtentPart().setUpdateRythm("");
		} else {
			metadata.getTemporalExtentPart().setUpdateRythm(listBox.getValue(listBox.getSelectedIndex()));
		}
	}

	@Override
	public void edit(MetadataDTO metadata) {
		ElementUtil.show(listBox);
		ElementUtil.hide(label);
		String aux = StringUtil.trimToEmpty(metadata.getTemporalExtentPart().getUpdateRythm());
		if (aux.length() > 0) {
			selectByValue(aux);
		} else {
			listBox.setSelectedIndex(UNSELECTED_ID_INDEX);
		}
	}

}
